from django.db import transaction
from rest_framework import serializers

from goods.models import SKUImage, SKU, SKUSpecification, SPU, GoodsCategory, SpecificationOption


class SKUImageSerializer(serializers.ModelSerializer):
    sku = serializers.StringRelatedField(label='一级商品名称')
    sku_id = serializers.IntegerField(label='商品ID')

    class Meta:
        model = SKUImage
        exclude = ('create_time', 'update_time')


class SKUSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')

    def validate_sku_id(self, value):
        try:
            SKU.objects.filter(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品ID不存在')
        return value

    def create(self, validated_data):
        sku_image = super().create(validated_data)
        sku = SKU.objects.get(id=sku_image['id'])

        if not sku.default_image:
            sku.default_image = sku_image.image
            sku.save()

        print(validated_data)
        print(sku_image)
        print(sku)
        return sku_image


class SKUSpecSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField(label='商品规格ID')
    option_id = serializers.IntegerField(label='选项ID')

    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ('id', 'name')


class SKUSerializer(serializers.ModelSerializer):
    category = serializers.StringRelatedField(label='三级分类名称')
    category_id = serializers.IntegerField(label='三级分类ID')
    spu_id = serializers.IntegerField(label='SPU的ID')
    specs = SKUSpecSerializer(label='商品规格', many=True)

    class Meta:
        model = SKU
        exclude = ('update_time', 'create_time', 'default_image', 'spu', 'comments')

    extra_kwargs = {
        'sales': {
            'read_only': True
        }
    }

    def validate(self, attrs):
        spu_id = attrs['spu_id']
        try:
            spu = SPU.objects.get(id=spu_id)
        except SPU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        attrs['category_id'] = spu.category3.id  # 外键，多对一

        # 检查skuui个数据是否有效

        specs = attrs['specs']
        spu_specs = spu.specs.all()
        spec_count = spu_specs.count()

        # SKU商品的规格数据是否完整
        if spec_count != len(specs):
            raise serializers.ValidationError('SKU规格数据不完整')

        # SKU商品的规格数据是否一致,分别教研sku和spu的规格
        specs_ids = [spec.get('spec_id') for spec in specs]
        spu_specs_ids = [spec.id for spec in spu_specs]

        specs_ids.sort()
        spu_specs_ids.sort()

        # 对比规格数据是否一致
        if spu_specs_ids != specs_ids:
            raise serializers.ValidationError('商品规格数据有误')

        # 检查spec_id对应的规格是否包含option_id对应的选项
        for spec in specs:
            spec_id = spec.get('spec_id')
            option_id = spec.get('option_id')

            # 数据库中option_id
            options = SpecificationOption.objects.filter(spec_id=spec_id)
            options_ids = [option.id for option in options]

            if option_id not in options_ids:
                raise serializers.ValidationError('规格选项数据有误')

            return attrs

    def create(self, validated_data):
        specs = validated_data.pop('specs')

        with transaction.atomic():
            sku = SKU.objects.create(**validated_data)

            for spec in specs:
                SKUSpecification.objects.create(
                    sku=sku,
                    spec_id=spec.get('spec_id'),
                    option_id=spec.get('option_id')
                )
        return sku

    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')  # 这是一个对象字典
        # instance=self.get_object(),
        # serializers.
        #


        with transaction.atomic():
            sku = super().update(instance, validated_data)
            # instance=self.get_objects()
            # serializer=self.get_serilizer(instance,date=validated_data)
            # serializer.is_valid(raise_exception=True)
            # serializer.save()
            instance.specs.all().delete()  #把原有的规格删除

            for spec in specs:
                SpecificationOption.objects.create(
                    sku=instance,
                    option_id=spec.get('option_id'),
                    spec_id=spec.get('spec_id')
                )
            # for spec in specs:
            #     SpecificationOption.objects.get(sku=instance).update(
            #         sku=instance,
            #         option_id=spec.get('option_id'),
            #         spec_id=spec.get('spec_id')
            #     )
        return sku










